package org.jeecg.common.oa.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.oa.entity.OaMessage;
import org.jeecg.common.oa.service.IOaMessageService;
import org.jeecg.common.oa.vo.OaMessageVo;
import org.jeecg.common.properties.config.OaPropertyConfig;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.HttpClientUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Configuration
@Slf4j
public class OaMessageUtils {

    @Autowired
    private OaPropertyConfig oaPropertyConfigBase;
    @Autowired
    private IOaMessageService oaMessageServiceBase;

    //当前工具类
    private static OaPropertyConfig oaPropertyConfig;
    private static IOaMessageService oaMessageService;

    //解决静态方法中不能直接用oaConfig的问题
    @PostConstruct
    public void init() {
        oaPropertyConfig = this.oaPropertyConfigBase;
        oaMessageService = this.oaMessageServiceBase;
    }

    /**
     * 发送审批完成消息
     * @param fromUser
     * @param toUser
     * @param messageContent
     */
    public static void sendCompleteMessage(LoginUser fromUser, LoginUser toUser, String messageContent) {
        sendMessage(fromUser, toUser, messageContent, oaPropertyConfig.getCompleteMessageURL(), oaPropertyConfig.getCompleteMessageH5URL());
    }

    /**
     * 发送审批提醒消息
     * @param fromUser
     * @param toUser
     * @param messageContent
     * @param currentId
     */
    public static void sendRemindMessage(LoginUser fromUser, LoginUser toUser, String messageContent, String currentId) {
        sendMessage(fromUser, toUser, messageContent, oaPropertyConfig.getMessageURL().replace("{CURRENT_ID}", currentId),
                oaPropertyConfig.getMessageH5URL().replace("{CURRENT_ID}", currentId));
    }

    /***
     * 单条发送消息到OA系统
     * @param fromUser
     * @param toUser
     * @param messageContent
     * @param messageUrl
     * @param h5Url
     */
    public static void sendMessage(LoginUser fromUser, LoginUser toUser, String messageContent, String messageUrl, String h5Url) {
//        if (toUser == null || StringUtils.isBlank(toUser.getId())) {
//            return;
//        }
//        if (fromUser == null || StringUtils.isBlank(fromUser.getId())) {
//            return;
//        }
//        if (toUser.getType() == null || toUser.getType().intValue() != DataSourcesTypeEnum.OA.getStatus()){
//            return;
//        }
//        OaMessage oaMessage = createOaMessage(fromUser, toUser, messageContent, messageUrl, h5Url);
//        OaMessageVo msg = createOaMessageVo(oaMessage);
//        String url = oaPropertyConfig.getSendMessage().replace("{TOKEN}", OaSyncUtils.getToke(false));
//        String resultString = null;
//        try {
//            resultString = HttpClientUtil.doPostJson(url, JSONObject.toJSONString(msg));
//            log.info("resultString：", resultString);
//            ResultEntity resultEntity = JSONObject.parseObject(resultString, ResultEntity.class);
//            if (resultEntity.getSuccess()) {
//                oaMessage.setStatus(ResultStatusEnum.SUCCESS.getStatus());
//            } else {
//                oaMessage.setStatus(ResultStatusEnum.FAIL.getStatus());
//            }
//            oaMessageService.updateById(oaMessage);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("单条发送消息，回写消息发送状态失败:", resultString);
//        }

    }

    /**
     * 群发消息到OA系统
     *
     * @param fromUser
     * @param toUsers
     * @param messageContent
     * @param messageUrl
     * @param h5Url
     */
    public static void sendMessageList(LoginUser fromUser, List<LoginUser> toUsers, String messageContent, String messageUrl, String h5Url) {

//        if (fromUser == null || StringUtils.isBlank(fromUser.getId())) {
//            return;
//        }
//        if (toUsers == null || toUsers.size() == 0) {
//            return;
//        }
//        List<OaMessageVo> messageVos = new ArrayList<>();
//        List<String> ids = new ArrayList<>();
//        OaMessage oaMessage = null;
//        for (LoginUser toUser : toUsers) {
//            if (toUser.getType() == null || toUser.getType().intValue() != DataSourcesTypeEnum.OA.getStatus()){
//                continue;
//            }
//            oaMessage = createOaMessage(fromUser, toUser, messageContent, messageUrl, h5Url);
//            OaMessageVo msg = createOaMessageVo(oaMessage);
//            messageVos.add(msg);
//            ids.add(oaMessage.getId());
//        }
//        if (messageVos.size() == 0){
//            return;
//        }
//        String url = oaPropertyConfig.getSendMessageList().replace("{TOKEN}", OaSyncUtils.getToke(false));
//        Map<String, Object> param = new HashMap<>();
//        param.put("messages", messageVos);
//        String resultString = null;
//        try {
//            resultString = HttpClientUtil.doPostJson(url, JSONObject.toJSONString(param));
//            log.info("resultString：", resultString);
//            ResultEntity resultEntity = JSONObject.parseObject(resultString, ResultEntity.class);
//            LambdaUpdateWrapper<OaMessage> updateWrapper = new LambdaUpdateWrapper<>();
//            updateWrapper.in(OaMessage::getId, ids);
//            OaMessage message = new OaMessage();
//            if (resultEntity.getSuccess()) {
//                message.setStatus(ResultStatusEnum.SUCCESS.getStatus());
//            } else {
//                message.setStatus(ResultStatusEnum.FAIL.getStatus());
//            }
////            updateWrapper.setEntity(message);
//            oaMessageService.update(message, updateWrapper);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("群发送消息，回写消息发送状态失败:", resultString);
//        }

    }

    /**
     * 创建消息保存到数据库
     *
     * @param fromUser
     * @param toUser
     * @param messageContent
     * @param messageUrl
     * @param h5Url
     * @return
     */
    private static OaMessage createOaMessage(LoginUser fromUser, LoginUser toUser, String messageContent, String messageUrl, String h5Url) {
        OaMessage msg = new OaMessage();
        msg.setRegisterCode(oaPropertyConfig.getRegisterCode());
        msg.setMessageContent(messageContent);
        msg.setSenderId(fromUser.getId());// 用户的唯一标识
        msg.setReceiverId(toUser.getId());//接收用户的唯一标识
        msg.setSenderName(fromUser.getRealname());
        msg.setReceiverName(toUser.getRealname());
        msg.setNoneBindingReceiver(toUser.getUsername());
        msg.setNoneBindingSender(fromUser.getUsername());
        msg.setCreationDate(DateUtils.now());
        // 参考接口说明，致远提供
        msg.setMessageType(oaPropertyConfig.getMessageType());
        msg.setDownloadUrl(oaPropertyConfig.getDownloadUrl());
        msg.setMessageUrl(messageUrl);
        msg.setMessageH5Url(h5Url);
        oaMessageService.save(msg);
        return msg;
    }

    /**
     * 创建发送消息对象
     *
     * @param oaMessage
     * @return
     */
    private static OaMessageVo createOaMessageVo(OaMessage oaMessage) {
        OaMessageVo msg = new OaMessageVo();
        msg.setThirdpartyRegisterCode(oaMessage.getRegisterCode());
        msg.setThirdpartyMessageId(oaMessage.getId()); // 消息的唯一标识
        msg.setMessageContent(oaMessage.getMessageContent());
        msg.setThirdpartySenderId(oaMessage.getSenderId());// 用户的唯一标识
        msg.setThirdpartyReceiverId(oaMessage.getReceiverId());//接收用户的唯一标识
        msg.setThirdpartySenderName(oaMessage.getSenderName());
        msg.setThirdpartyReceiverName(oaMessage.getReceiverName());
        msg.setNoneBindingReceiver(oaMessage.getNoneBindingReceiver());
        msg.setNoneBindingSender(oaMessage.getNoneBindingSender());
        msg.setCreationDate(oaMessage.getCreationDate());
        // 参考接口说明，致远提供
        msg.setMessageType(oaMessage.getMessageType());
        msg.setDownloadUrl(oaMessage.getDownloadUrl());
        msg.setMessageURL(oaMessage.getMessageUrl());
        msg.setMessageH5URL(oaMessage.getMessageH5Url());
        return msg;
    }


    public static void testSendMessage() {
        OaMessageVo msg = new OaMessageVo();
        msg.setThirdpartyRegisterCode("3001");
        msg.setThirdpartyMessageId(UUIDGenerator.generate()); // 消息的唯一标识
        msg.setMessageContent("您有一条公文待处理。");
        msg.setThirdpartySenderId("test");// 用户的唯一标识
        msg.setThirdpartyReceiverId("test");//接收用户的唯一标识
        msg.setThirdpartySenderName("测试");
        msg.setThirdpartyReceiverName("测试");
        msg.setNoneBindingReceiver("test");
        msg.setNoneBindingSender("test");
        msg.setCreationDate(DateUtils.now());
        // 参考接口说明，致远提供
        msg.setMessageType(4);
        msg.setDownloadUrl("");
        msg.setMessageURL("http://192.168.0.104:9000/#/activiti/todoManage??currentId=5037");
        msg.setMessageH5URL("http://192.168.0.104:9000/#/activiti/todoManage??currentId=5037");
//        String url = oaConfig.getSendMessage().replace("{TOKEN}", OaSyncUtils.getToke(false));
//        String url = "http://www.cqukon.com:8081/seeyon/rest/thirdpartyMessage/receive/singleMessage?token=4b10897e-4d86-4745-9fd6-7a5b56ee5943";
        String url = "http://192.168.0.106/seeyon/rest/thirdpartyMessage/receive/singleMessage?token=08f47ba6-66bd-475e-b1b8-dfc5088a219d";
        String resultString = HttpClientUtil.doPostJson(url, JSONObject.toJSONString(msg));
        System.out.println(resultString);

    }

    public static void main(String[] args) {
        testSendMessage();
    }

}
